import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Form,
  Input,
  Card,
  message,
  Button,
  Row,
  Col,
  Tooltip,
} from 'antd';

import uuid from 'uuid';
import ImageUploader from './Attachment/ImageUploader';
import CustomerSelector from '../../components/Falcon/CustomerSelector';
import FamilyMemberSelector from '../../components/Falcon/FamilyMemberSelector';

const FormItem = Form.Item;
const costomerRelationArray = ["本人", "父/母", "配偶", "子/女", "兄弟/姐妹", "其他"];


import { solo } from '../../common/solo';
 
@connect(({ risk, apply }) => ({
  risk, apply
}))
@Form.create()
export default class CustomerInfoEditor extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      customerSelectorVisible: false,
      familyMemberSelectorVisible: false,
      name: '',
      customer: null,
      familyMember: null,
      customerId: '',
      key: uuid.v4(),
    };
  }

  componentDidMount() {
    // //
    //this.setState({customer: data});
    // const { apply } = this.props;
    // const { applyDetails } = apply;
    // if(this.props.typeState){
    //   console.log("componentDidMount 3333333333", applyDetails.customers)
    //   applyDetails&&applyDetails.customers.map(item => {
    //     switch (item.state) {
    //       case 1:
    //       this.setState({
    //         customer: item,
    //       })
    //         break;
    //       case 2:
    //       this.setState({
    //         familyMember: item,
    //       })
    //         break;
    //       case 3:
    //       this.setState({
    //         familyMember: item,
    //       })
    //         break;
    //     }
    //   })
    // }
    // console.log("componentDidMount 111111111", this.state.customer)
    // console.log("componentDidMount 222222222", this.state.familyMember)
  }


  // changeCustomer(data) {
  //   this.setState({customer: data});
  // }

  /**
   * user action methods
   */
  handleSelectCustomerClick = () => {
    this.setState({
      customerSelectorVisible: true,
    });
  };

  handleSelectFamilyMemberClick = () => {

    // const { risk: { customerDetails } } = this.props;
    // if (customerDetails && customerDetails.id) {
    //   this.setState({
    //     familyMemberSelectorVisible: true,
    //   });
    // } else {
    //   message.warning("请先选择主申请人")
    // }

    const { mainApplyer } = this.props;
    if (mainApplyer) {
      this.setState({
        familyMemberSelectorVisible: true,
      }, () => {
        //loadDataFromServer
        if (this.familyMemberFormRef) {
          this.familyMemberFormRef.loadDataFromServer();
        }
      });
    } else {
      message.warning("请先选择主申请人")
    }
  };

  /**
   * modal handler methods (customerSelector)
   */
  handleFamilyMemberSelected = () => {
    const { dispatch } = this.props;
    const customer = this.familyMemberFormRef.state.familyMemberDetails;
    customer.state = this.props.data.state;

    this.setState({
      familyMemberSelectorVisible: false,
    }, () => {
      // console.log('handleFamilyMemberSelected', customer);
      if (this.props.onCustomerSelected) {
        // console.log('will handleFamilyMemberSelected', customer);
        this.props.onCustomerSelected(customer);
      }
    });
    // this.setState({
    //   //familyMember: this.familyMemberFormRef.state.familyMemberDetails,
    //   //familyMemberSelectorVisible: false,
    //   //customer: null,
    //   customer: this.familyMemberFormRef.state.familyMemberDetails,
    //   familyMemberSelectorVisible: false,
    //   familyMember: null,
    // }, () => {
    // });
  };

  handleFamilyMemberCancel = () => {
    this.setState({
      familyMemberSelectorVisible: false,
    });
  };
  saveCustomerFormRef = formRef => {
    this.customerFormRef = formRef;
  };

  saveFamilyMemberFormRef = formRef => {
    this.familyMemberFormRef = formRef;
  };
  /**
   * modal handler methods (customerSelector)
   */
  handleCustomerSelected = () => {
    const { dispatch } = this.props;
    const customer = this.customerFormRef.state.customerDetails;
    customer.state = 1;
    // // console.log('this.formRe爱仕达大多.: ', this.customerFormRef.state.customerDetails.id);
    // dispatch({
    //   type: 'risk/setCustomerDetails',
    //   payload: customer,
    // });
    // this.setState({
    //   customer: customer,
    //   familyMember: null,
    //   customerSelectorVisible: false,
    // });
    this.setState({
      customerSelectorVisible: false,
    }, () => {
      // console.log('handleCustomerSelected', customer);
      if (this.props.onCustomerSelected) {
        // console.log('will onCustomerSelected', customer);
        this.props.onCustomerSelected(customer);
      }
    });
  };

  // handleRemoveImage = (fieldName, fileInfo) => {
  //   if (this.props.onAttachmentRemove) {
  //     this.props.onAttachmentRemove(fieldName, fileInfo);
  //   }
  // };

  handleCustomerCancel = () => {
    this.setState({
      customerSelectorVisible: false,
    });
  };

  handleImageUploaded = (fieldName, fileList, ) => {
    // console.log("3242432424", fileList)
    if (this.props.onCustomerImageUploaded) {
      this.props.onCustomerImageUploaded(this.props.data, fieldName, fileList);
    }
  };


  handleRemoveImage = (fieldName, fileList) => {
    // const newFileList = this.state.fileList.filter((item,index)=>{
    //   return fileInfo.key !=  item.key;
    // });
    // this.setState({
    //   fileList: newFileList,
    // });
    const type = true;
    // const fileList = [];
    if (this.props.onCustomerImageUploaded) {
      this.props.onCustomerImageUploaded( this.props.data, fieldName, fileList, type);
    }   
  };

  collectCustomerInfo = () => {
    let error = null;
    let values = [];
    const { validateFieldsAndScroll } = this.props.form;
    validateFieldsAndScroll((_error, _values) => {
      error = _error;
      values = _values;
    });
    return {
      error,
      values,
    };
  };

  render() {
    const { risk, isForFamilyMember } = this.props;
    const { getFieldDecorator } = this.props.form;
    // console.log("this.propr.typeState", this.props.typeState)
    //const {customer} = this.state;
    const customer = this.props.data;

    // const fileList = [{ "key": "6426339434723016704.jpg", "url": "http://112.64.161.203:9020/files/6426339434723016704.jpg", "status": "done", "uid": "6426339434723016704.jpg", "name": "6426339434723016704.jpg" }]

    return (
      <Card bordered={false}>
        <Form layout="vertical" hideRequiredMark>
          {/* {JSON.stringify(this.calcFileList('idcardFrontImg'))} */}
          <Row gutter={16}>
            <Col lg={5} md={12} sm={24}>
              <FormItem label="客户姓名" >
                <Row gutter={16}>
                  <Col span={21}>
                    <Input readOnly={true} value={this.calcCustomerName()} />
                  </Col>
                  <Col span={3}>
                    {isForFamilyMember ? (
                      <Tooltip title="从关系人中选择">
                        <Button
                          onClick={this.handleSelectFamilyMemberClick}
                          style={{ marginLeft: '10px' }}
                          type="dashed"
                          size="small"
                          shape="circle"
                          icon="search"
                        />
                      </Tooltip>
                    ) : (
                        <Tooltip title="从已有客户中选择">
                          <Button
                            onClick={this.handleSelectCustomerClick}
                            style={{ marginLeft: '10px' }}
                            type="dashed"
                            size="small"
                            shape="circle"
                            icon="search"
                          />
                        </Tooltip>
                      )}
                  </Col>
                </Row>
              </FormItem>
            </Col>
            <Col lg={6} md={12} sm={24} offset={1}>
              <FormItem label="证件号码" >
                {/* {getFieldDecorator('idcard', {
                initialValue: this.calcCustomerIdCard(),
                rules: [{ required: true, message: '请输入身份证号码' }],
              })( */}
                <Input readOnly={true} value={this.calcCustomerIdCard()} />
                {/* )} */}
              </FormItem>
            </Col>
            <Col lg={5} md={12} sm={24} offset={1}>
              <FormItem label="联系电话" >
                {/* {getFieldDecorator('phone', {
                initialValue: this.calcCustomerPhone(),
                rules: [{ required: true, message: '请输入联系电话' }],
              })( */}
                <Input readOnly={true} value={this.calcCustomerPhone()} />
                {/* // )} */}
              </FormItem>
            </Col>
            <Col lg={5} md={12} sm={24} offset={1}>
              <FormItem label="客户关系" >
                {/* {getFieldDecorator('phone', {
                initialValue: this.calcCustomerPhone(),
                rules: [{ required: true, message: '请输入联系电话' }],
              })( */}
                <Input readOnly={true} value={this.calcCustomerRelation()} />
                {/* // )} */}
              </FormItem>
            </Col>
          </Row>
          {/* {console.log("customerInfo", customer)} */}
          <Row>
            <Col span={5}>
              <FormItem label="身份证正面">
                <ImageUploader
                  maxCount={1}
                  customerInfo={customer}
                  fieldName="idcardFrontImg"
                  showRemoveIconType={true}
                  size="large"
                  onRemoveImage={this.handleRemoveImage}
                  fileList={this.calcFileList('idcardFrontImg')}
                  onImageUploaded={this.handleImageUploaded}
                  attachmentData={{
                    projectId: '', //业务ID
                    customerId: customer.id, //客户ID
                    attachType: '0', //0：图片；1：视频
                    attachKind: '1111', //附件种类
                    type: '身份证正面', //图片类型 
                  }}
                />
              </FormItem>
            </Col>
            <Col span={5}>
              <FormItem label="身份证反面" >
                <ImageUploader maxCount={1}
                  fieldName="idcardBackImg"
                  customerInfo={customer}
                  showRemoveIconType={true}
                  size="large"
                  onRemoveImage={this.handleRemoveImage}
                  fileList={this.calcFileList('idcardBackImg')}
                  onImageUploaded={this.handleImageUploaded}
                  attachmentData={{
                    projectId: '', //业务ID
                    customerId: customer.id, //客户ID
                    attachType: '0', //0：图片；1：视频
                    attachKind: '1112', //附件种类
                    type: '身份证反面', //图片类型 
                  }}
                />
              </FormItem>
            </Col>
            <Col span={5}>
              <FormItem label="授权书">
                <ImageUploader maxCount={1}
                  fieldName="authority"
                  customerInfo={customer}
                  size="large"
                  showRemoveIconType={true}
                  onRemoveImage={this.handleRemoveImage}
                  fileList={this.calcFileList('authority')}
                  onImageUploaded={this.handleImageUploaded}
                  attachmentData={{
                    projectId: '', //业务ID
                    customerId: customer.id, //客户ID
                    attachType: '0', //0：图片；1：视频
                    attachKind: '1121', //附件种类
                    type: '授权书', //图片类型 
                  }}
                />
              </FormItem>
            </Col>
            <Col span={5}>
              <FormItem label="签字照">
                <ImageUploader maxCount={1}
                  fieldName="sign"
                  customerInfo={customer}
                  size="large"
                  showRemoveIconType={true}
                  fileList={this.calcFileList('sign')}
                  onRemoveImage={this.handleRemoveImage}
                  onImageUploaded={this.handleImageUploaded}
                  attachmentData={{
                    projectId: '', //业务ID
                    customerId: customer.id, //客户ID
                    attachType: '0', //0：图片；1：视频
                    attachKind: '1122', //附件种类
                    type: '签字照', //图片类型 
                  }}
                />
              </FormItem>
            </Col>
            <Col span={4}>
              <FormItem label="其他照片">
                <ImageUploader maxCount={1}
                  fieldName="otherCredit"
                  customerInfo={customer}
                  size="large"
                  showRemoveIconType={true}
                  fileList={this.calcFileList('otherCredit')}
                  onRemoveImage={this.handleRemoveImage}
                  onImageUploaded={this.handleImageUploaded}
                  attachmentData={{
                    projectId: '', //业务ID
                    customerId: customer.id, //客户ID
                    attachType: '0', //0：图片；1：视频
                    attachKind: '1123', //附件种类
                    type: '其他照片', //图片类型 
                  }}
                />
              </FormItem>
            </Col>
          </Row>
          <CustomerSelector
            visible={this.state.customerSelectorVisible}
            onOk={this.handleCustomerSelected}
            onCancel={this.handleCustomerCancel}
            wrappedComponentRef={this.saveCustomerFormRef}
          />
          <FamilyMemberSelector
            visible={this.state.familyMemberSelectorVisible}
            data={this.props.mainApplyer}
            onOk={this.handleFamilyMemberSelected}
            onCancel={this.handleFamilyMemberCancel}
            wrappedComponentRef={this.saveFamilyMemberFormRef}
          />
        </Form>
      </Card>
    );
  }

  calcCustomerName = () => {
    //const { customer, familyMember } = this.state;
    const customer = this.props.data;
    if (customer) {
      // this.customeerDetails = customer;
      return customer.custName;
    }

    // if (familyMember) {
    //   return familyMember.custName;
    // }
    return null;
  }

  calcCustomerIdCard = () => {
    // const { customer, familyMember } = this.state;

    const customer = this.props.data;

    if (customer) {
      return customer.idcard;
    }

    // if (familyMember) {
    //   return familyMember.idcard;
    // }
    return null;
  }

  calcCustomerPhone = () => {
    //const { customer, familyMember } = this.state;

    const customer = this.props.data;

    if (customer) {
      return customer.phone;
    }

    // if (familyMember) {
    //   return familyMember.phone;
    // }
    return null;
  }

  calcCustomerRelation = () => {
    //const { customer, familyMember } = this.state;

    const customer = this.props.data;

    if (customer) {
      return costomerRelationArray[customer.relation];
    }

    // if (familyMember) {
    //   return familyMember.relation;
    // }
    return null;
  }

  calcFileList = (fieldName) => {
    const customer = this.props.data;
    // console.log("calcFileList", customer)
    if (customer && customer.attachs) {
      // if (customer && customer.id) {
      const keyList = customer.attachs[fieldName];
      if (!keyList) {
        return [];
      }
      const imageInfoList = keyList.map((key) => {
        return {
          key,
          url: `${solo.imgShow}${key}`,
          status: 'done',
          uid: key,
          name: key,
        };
      });
      // console.log("imageInfoList", imageInfoList)
      return imageInfoList;
    }
    // console.log("calcFileList111111", customer)
    return [];
  }

}
